import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

// 创建一个异步的 thunk
export const fetchList = createAsyncThunk(
    'list/fetchList', // action 的类型
    async (params, { rejectWithValue }) => {
        try {
            const response = await axios.get('/shop/list', { params });
            return response.data; // 返回数据
        } catch (error) {
            return rejectWithValue(error.message); // 错误信息
        }
    }
);


export const ListSlice = createSlice({
    name:'list',
    initialState: {
        list: [],
        hasMore: true,
        currentPageCode: 1,
        loading: false,
        error: null,
    },
    reducers:{
        // getList:state=>{
        //     axios.get('shop/list',{params:{pageCode:1,pageSize:20}}).then(res=>{
        //         const {data:data1} = res;
        //         const { totalCount,data} = data1 || {};
        //         state.list = data.data
        //         state.totalCount = data.totalCount;
        //         console.log('data', data, data.totalCount);
        //     }).catch(err=>{console.log('err',err);})
        // }
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchList.pending, (state) => {
                state.loading = true; // 请求开始时设置 loading 为 true
                state.error = null; // 清除之前的错误
            })
            .addCase(fetchList.fulfilled, (state, action) => {
                const { data, totalCount } = action.payload || {};
               const index = data.data.findIndex(item => state.list.findIndex(it=>it.id===item.id)>-1)
                console.log('index', state.list,index);
                if (index>-1) return 
                state.list = [...state.list,...data.data] || [];
                state.hasMore = state.list.length < data.totalCount 
                state.loading = false; // 请求成功时设置 loading 为 false
                state.currentPageCode += 1
                // console.log('state.currentPageCode', state.currentPageCode);
            })
            .addCase(fetchList.rejected, (state, action) => {
                state.loading = false; // 请求失败时设置 loading 为 false
                state.error = action.payload || 'Failed to fetch data'; // 设置错误信息
            });
    },

})


export default ListSlice.reducer;
